const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});
const db = cloud.database();
const startCheckIn = async (event) => {
  const { groupID, isCheckIn } = event;
  const transaction = await db.startTransaction();

  try {

    if (isCheckIn) {
      // 更新活动群组信息表中的签到相关字段
      const result = await transaction.collection('Activity_Group_Information')
        .where({
          _ID: groupID
        })
        .update({
          data: {
            IsCheckedOut: false
          }
        });
      // 检查更新是否成功
      if (result.stats.updated > 0) {
        await transaction.commit();
        return true;
      } else {
        await transaction.rollback();
        return false;
      }

    }
    else {
      const result = await transaction.collection('Activity_Group_Information')
        .where({
          _ID: groupID
        })
        .update({
          data: {
            IsCheckedIn: false,
          }
        });
      // 检查更新是否成功（至少更新了一条记录）
      if (result.stats.updated > 0) {
        await transaction.commit();
        return true;
      } else {
        // 没有找到匹配的记录，回滚事务
        await transaction.rollback();
        return false;
      }
    }
  } catch (err) {
    await transaction.rollback();
    return false;
  }
};

exports.main = async (event, context) => {
  return await startCheckIn(event);
};